package web

import (
	"ginweb/module/router"
	"io"
	"os"

	"github.com/gin-gonic/gin"
)

var (

	// Host 端口
	Host string = ":8080"

	// Gin 框架实例
	Gin *gin.Engine
)

// Init Web服务器框架
func Init() *gin.Engine {

	gin.DisableConsoleColor()

	// Logging to a file.
	f, err := os.Create("gin.log")
	if err != nil {
		println(err.Error())
	}

	gin.DefaultWriter = io.MultiWriter(f)
	Gin = gin.Default()

	Gin.Use(cors)
	router.Load(Gin)

	return Gin
}

// cors跨域
func cors(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
	c.Header("Access-Control-Allow-Methods", "*")
	c.Header("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Token")
	c.Header("Access-Control-Allow-Credentials", "true")
	if c.Request.Method == "OPTIONS" {
		c.String(200, "request ok!")
		c.Abort()
	}

}
